package demo;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 苏李涛
 * Date: 2024-10-18
 * Time: 17:08
 */

// 通过懒汉模式构造单例模式

//1.初级版本
class SingletonLazy{
    private static SingletonLazy instance = null;
    private static Object locker = new Object();

    public static SingletonLazy getInstance() {

            if (instance == null) {
                //涉及修改操作线程可能不安全，要加锁实现原子性，加上锁也可能导致多个线程访问带来性能差问题
                instance = new SingletonLazy();//这里也可能由于编译器优化导致指令重排序问题
            }

        return instance;
    }

    private SingletonLazy() {

    }
}

//2.终极版本

class SingletonLazy2{
    private static volatile SingletonLazy2 instance = null;
    private static Object locker = new Object();

    public static SingletonLazy2 getInstance() {
        if(instance == null) {
            synchronized (locker) {
                if (instance == null) {
                    instance = new SingletonLazy2();
                }
            }
        }

        return instance;
    }

    private SingletonLazy2() {

    }
}

public class Demo2 {
    public static void main(String[] args) {

    }
}
